<?php
namespace Qgs\Controller;
use Qgs\Model\B2cOrdersModel;
use Home\Event\LetterEvent;
use Home\Event\WeixinEvent;

/**
 * Class 页面管理-首页轮播
 * @package Qgs\Controller
 */

class OrdersController extends BaseController  {

    public $local_id;

    public function __construct()
    {
        parent::__construct();

        $this->local_id = session('userInfo')['local_id'];
    }
    /**
     * 店铺订单列表
     */
    public function orderList(){


        $p = I('p',1,'intval');
        $view = I('get.view',0,'intval');

        //文字描述
        $isDes = array(
            0=>'待发货',
            1=>'已发货',
            2=>'已收货',
            3=>'待支付',
            4=>'已作废',
            5=>'已完成',
            6=>'全部',
        );


        $Model = new B2cOrdersModel();
        $orderList = $Model->orderList($p,$view);

        $this->assign('view',$view);
        $this->assign('isDes',$isDes[$view]);

        $this->assign('page',$orderList['page']);// 赋值分页输出
        $this->assign('payList',$orderList['list']);
        $this->display('Orders/orderList');

    }

    /**
     *
     * 订单详情
     *
     */

    public function  orderDetail(){

        $orderId = I('get.id');
        $Model = new B2cOrdersModel();

        $orDetail = $Model->orderDetail($orderId);

        //售后申请商品
        foreach ($orDetail['product'] as $k=>$value){

            $is_refund[$k] = M('b2c_refund_money_goods mg')
                ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.local_id'=>session('userInfo.local_id'),'m.status'=>['not in','0,6,7'],
                'm.type'=>'1'])
                ->field('it.*,m.price as backprice,mg.num')
                ->order('m.id desc')
                ->find();
            if(empty($is_refund[$k])){
                unset($is_refund[$k]);
                continue;
            }


            $is_refund[$k]['istype'] = '发货前：退款';
            $is_refund[$k]['bn'] = $value['bn'];
            $is_refund[$k]['name'] = $value['name'];
            $is_refund[$k]['barcode'] = $value['barcode'];
            $is_refund_tree[$k]['price'] = $value['price'];
            $is_refund[$k]['sendnum'] = $value['sendnum'];
            $is_refund[$k]['nums'] = $value['nums'];
            $is_refund[$k]['amount'] = $value['amount'];

        }
        //发货后 售后退款
        foreach ($orDetail['product'] as $k=>$value){

            $is_refund_two[$k] = M('b2c_refund_money_goods mg')
                ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.local_id'=>session('userInfo.local_id'),'m.status'=>['not in','0,6,7'],
                    'm.type'=>'2'])
                ->field('it.*,m.price as backprice,mg.num')
                ->order('m.id desc')
                ->find();
            if(empty($is_refund_two[$k])){
                unset($is_refund_two[$k]);
                continue;
            }


            $is_refund_two[$k]['istype'] = '发货后：售后退款';
            $is_refund_two[$k]['bn'] = $value['bn'];
            $is_refund_two[$k]['name'] = $value['name'];
            $is_refund_tree[$k]['price'] = $value['price'];
            $is_refund_two[$k]['barcode'] = $value['barcode'];
            $is_refund_two[$k]['sendnum'] = $value['sendnum'];
            $is_refund_two[$k]['nums'] = $value['nums'];
            $is_refund_two[$k]['amount'] = $value['amount'];

        }

         //发货后 售后退货退款
        foreach ($orDetail['product'] as $k=>$value){

            $is_refund_tree[$k] = M('b2c_refund_money_goods mg')
                ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.local_id'=>session('userInfo.local_id'),'m.status'=>['not in','0,6,7'],
                    'm.type'=>'3'])
                ->field('it.*,m.price as backprice,mg.num')
                ->order('m.id desc')
                ->find();

            if(empty($is_refund_tree[$k])){
                unset($is_refund_tree[$k]);
                continue;
            }


            $is_refund_tree[$k]['istype'] = '发货后：退货退款';
            $is_refund_tree[$k]['bn'] = $value['bn'];
            $is_refund_tree[$k]['name'] = $value['name'];
            $is_refund_tree[$k]['price'] = $value['price'];
            $is_refund_tree[$k]['barcode'] = $value['barcode'];
            $is_refund_tree[$k]['sendnum'] = $value['sendnum'];
            $is_refund_tree[$k]['nums'] = $value['nums'];
            $is_refund_tree[$k]['amount'] = $value['amount'];

        }

        if($orDetail['status']===0){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }


        $butt ='';
        if ( $orDetail['detail']['refund_front_status'] == '1') {
            $butt = "<a class='btn btn-info'  href='/Qgs/Refund/index/view/1.html' style='width: 80px;' >客户退款</a></li>";
        } elseif($orDetail['detail']['pay_status'] == '1' && ($orDetail['detail']['ship_status'] == '0' || $orDetail['detail']['ship_status'] == '2')
        && $orDetail['detail']['status'] == 'active') {
            $urlDeli = U("orders/orderDelivery/", ['id' => $orDetail['detail']['order_id']]);
            $butt = "<a href='#' class='suggest btn btn-info' data-id='$urlDeli'  style='width: 80px;'>发货</a>";
        }

        $supplier = $Model->getSupplierDetail($orderId);

        $this->assign('butt',$butt);
        $this->assign('orDetail',$orDetail);
        $this->assign('isrefund',$is_refund);
        $this->assign('isrefundtwo',$is_refund_two);
        $this->assign('isrefundtree',$is_refund_tree);
        $this->assign('supplier', $supplier);
        $this->display('Orders/orderDetail');

    }

    /**
     * 订单备注
     */
    public function orderMark(){

        $Model = new B2cOrdersModel();
        $result = $Model->markList(I('get.id'));
        $this->assign('orderMark',$result);
        $this->assign('order_id',I('get.id'));
        $this->display('Orders/orderMark');

    }

    /**
     * 保存备注
     */
    public function saveMark(){
        $Model = new B2cOrdersModel();

        if(empty(I('post.mark'))){
            $this->ajaxReturn(['msg'=>'备注不能为空','status'=>0]);
        }

        $result = $Model->saveMark(I('post.id'),I('post.mark'));



        $this->ajaxReturn($result);

    }

    /**
     * 订单日志
     */
    public function orderLog(){
        $Model = new B2cOrdersModel();

        $result = $Model->ordreLog(I('get.id'));

        if($result['status']===0){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            return false;
        }

        $this->assign('order_id',I('get.id'));
        $this->assign('logList',$result);
        $this->display('Orders/orderLog');
    }


    /**
     * 订单发货详情
     */

    public function orderDelivery(){
        $Model = new B2cOrdersModel();

        $result = $Model->ordreDe(I('get.id'));
        $lastResult = $this->isCanDeliveryGoods($result);

        if($result['status']===0){
            echo "<script>alert('参数错误');history.go(-1);</script>";
            exit;
        }

       // print_r($result);exit;
        $this->assign('delivery',$lastResult);
        $this->display('Orders/orderDelivery');
    }


    public function isCanDeliveryGoods($result){

        //售后申请商品
        foreach ($result['product'] as $k=>$value){
            $is_id = M('b2c_refund_money')
                ->where(['order_id'=>$value['order_id'],'local_id'=>session('userInfo.local_id'),'status'=>['neq','0']])
                ->order('id desc')
                ->find()['id'];
            if(!empty($is_id)){
                break;
            }
        }

        if(!empty($is_id)){

            foreach ($result['product'] as $k=>$value){
                $is_refund = array();
                $is_refund = M('b2c_refund_money_goods mg')
                    ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
                    ->join("left join ".C('DB_PREFIX')."b2c_order_items it on it.item_id = mg.item_id")
                    ->where(['m.order_id'=>$value['order_id'],'mg.item_id'=>$value['item_id'],'m.local_id'=>session('userInfo.local_id'),'m.status'=>['eq','5'],
                        'm.id'=>$is_id])
                    ->order('m.id desc')
                    ->find();



                if(!empty($is_refund)){

                    if($is_refund['nums']-$is_refund['num']==0){

                        $result['product'][$k]['needsend']= $is_refund['nums']-$is_refund['num'];

                    }else{
                        $result['product'][$k]['needsend']= $is_refund['nums']-$is_refund['num'];

                    }
                    $result['product'][$k]['backsend']= '已经申请退款商品数量：'.$is_refund['num'];
                    unset($is_refund);


                    continue;
                }

            }
        }

        return $result;
    }

    /**
     * 生成发货单，发货详细表 sdb_b2c_delivery sdb_b2c_delivery_items  减少库存
     */
    public function doDelivery(){

        $Model = new B2cOrdersModel();
        $delivery_id = $Model->gen_id();

        $arrDelivery = $_POST;
        $orderGoodsDetail = $Model->orderDetail($arrDelivery['order_id']);

        if($orderGoodsDetail['detail']['ship_status']=='1'){
            $this->ajaxReturn(array('msg'=>'该订单已经发货','status'=>1));
        }
        if($orderGoodsDetail['detail']['refund_front_status']=='1'){
            $this->ajaxReturn(array('msg'=>'该订单已经申请退款','status'=>1));
        }


        $orderGoods = $this->isCanDeliveryGoods($orderGoodsDetail);

        //自提 默认确认收货时间 3天，快递7天
      /*  if($orderGoods['detail']['is_zt']==1){
            $arr_delivery_time = array('order_id'=>$arrDelivery['order_id'],'delivery_time'=>time()+3*24*3600,'finish_time'=>time()+10*24*3600);
        }else{*/
            $arr_delivery_time = array('order_id'=>$arrDelivery['order_id'],'delivery_time'=>time()+7*24*3600,'finish_time'=>time()+14*24*3600);
       /* }*/


        //事物开启
        $Mod = M();
        $Mod->startTrans();

        $resultItems = false;
        $is_up = false;
        $addResult = false;
        $change_OK = false;


        // 发货状态 更改
         $data = $_POST;



        $process['order_id'] = $arrDelivery['order_id'];
        $process['local_id'] = session('userInfo.local_id');
        $process['item_type'] = '2';
        $process['shipper_name'] = $arrDelivery['delivName'];
        $process['mobile'] = $arrDelivery['delivMobile'];
        $process['create_time'] = time();
        $process['memo'] = $arrDelivery['memo'];


        $isProcess = M('b2c_delivery_process')->data($process)->add();

        //入库 自动确认收货表
        $is_dly_time = M('b2c_order_delivery_time')->data($arr_delivery_time)->add();

        //生成发货单
         $result =   $Model->createDelivery($_POST,$delivery_id);

        if($result['status'] == 0){
            $this->ajaxReturn($result);
        }


        //更改订单orders表的 订单状态
        $isMsgChange =   M('b2c_orders')->where(['order_id'=>$arrDelivery['order_id']])->save(['order_msg'=>'已发货']);

        //生成发货单详细 sdb_b2c_delivery_items
        $resultItems =   $Model->createDeItems($_POST,$delivery_id,$orderGoods);
        //生成订单发货【货品明细】
        $create_detail = $Model->createOrderDeli($arrDelivery,$delivery_id,$orderGoods);

        if($create_detail['status']== 0){
            $this->ajaxReturn($create_detail);
        }


       if($result!==false){

            //更新order_items发货数量  更新b2c_orders 状态
            $is_up =  $Model->orderItems($arrDelivery,$orderGoods);
            //添加操作人员操作日志
           $addResult = $Model->addOrderLog($arrDelivery,$orderGoods);


            //发货成功，操作店铺商品表，减少库存  -1  -1
           $change_OK = $Model->storeChange($arrDelivery,$orderGoods);

            if($change_OK['status']==1){
                $change_OK = true;
            }else{
                $this->ajaxReturn(array('msg'=>'发货失败，库存异常','status'=>1));
            }

       }


        if ( $result !== false && $resultItems !== false && $create_detail['status'] !== 0 && $is_up !== 0 && $addResult !== false && $change_OK['status'] !== 0 && $isProcess !== false && $isMsgChange !== false && $is_dly_time !==false){

            //查询物流方式
            if($arrDelivery['logi_id']){
                $logi_name = M('b2c_store_dlycorp')->where(['corp_id' => $arrDelivery['logi_id'],'local_id' => $this->local_id])->find()['name'];
                $logi_no = $arrDelivery['logi_no'];
            }else{
                $logi_name = '门店配送';
                $logi_no = 0;
            }
            //推送微信消息
            $wxStatus = $this->sendWX($orderGoodsDetail['detail']['member_id'],$arrDelivery['order_id'],$logi_name,$logi_no);
            if($wxStatus != 2){
                //发货成功，发送短信
                $statusLetter = $this ->sendLetter($arrDelivery['order_id'],$logi_name,$logi_no,$orderGoodsDetail['detail']['member_id']);
            }


            // 提交事务
            $Mod->commit();
            if($wxStatus == 2){
                $this->ajaxReturn(array('msg'=>'发货成功，推送微信信息失败！','status'=>1));
            }elseif($statusLetter == 2){
                $this->ajaxReturn(array('msg'=>'发货成功，发送短信失败！','status'=>1));
            }
            $this->ajaxReturn(array('msg'=>'发货成功','status'=>1));
        }else{
            // 事务回滚
            $Mod->rollback();
           $this->ajaxReturn(array('msg'=>'发货失败','status'=>0));
        }

    }

    /**
     * 发送短信
     * @param $order_id 订单号
     * @param $logi_no 物流号
     * @param $logi_name 物流方式
     * $mobile 收货人手机号
     * @return int 0-禁用、1-成功、2-失败
     */
    public function sendLetter($order_id,$logi_name,$logi_no,$member_id){
        $letter_obj = new LetterEvent();

        //查询当前店铺短信模板
        $where = ['slt_id' => 1,'local_id' => $this->local_id,'status' => 1];
        $letter = M('store_letter')->where($where)->find();
        //dump($letter);
        if(!$letter){
            return 0;
        }
        //查询会员手机号
        $mobile = M('b2c_members')->where(['member_id' => $member_id])->find()['mobile'];
        if(!$mobile){
            return 0;
        }
        //拼短信内容
        $content = str_replace("{%order_id}",$order_id,$letter['content']);
        $content = str_replace("{%time}",date('Y-m-d H:i:s'),$content);
        $content = str_replace("{%store_name}",$logi_name,$content);
        $content = str_replace("{%logi_no}",$logi_no,$content);
        $status = $letter_obj->sendLetter($mobile,$content);
        if($status['status'] === true){
            return  1;
        }else{
            // 短信发送失败记录日志
            $add_data = [
                'order_id' => $order_id,
                'mobile' => $mobile,
                'type' => 2,
                'errcode' => $status['status'],
                'errmsg' => $status['msg'],
                'create_time' => time(),
                'status' => 2,
            ];
            M('push_message_log')->add($add_data);
            return 2;
        }

    }

    /**
     * @param $member_id 收货人id
     * @param $order_id 订单id
     * @param $logi_name 快递公司
     * @param $logi_no 快递单号
     * @return int 0-不推送、1-成功、2-失败
     */
    public function sendWX($member_id,$order_id,$logi_name,$logi_no){
        //查询会员的openid
        $openId = M('b2c_members m')
            ->field('t.openid')
            ->join("left join ".C('DB_PREFIX')."b2c_temp_user t on t.mobile = m.mobile")
            ->where(['member_id'=>$member_id])
            ->find()['openid'];
        if(!$openId){
            return 0;
        }
        $muban = M('store_wx_information a')
            ->join(C('DB_PREFIX')."wx_information b on a.wx_id = b.wx_id")
            ->field('b.*')
            ->where(['a.local_id' => $this->local_id,'a.wx_id' => 1,'a.status' => 1])
            ->find();
        //该店铺不推送消息
        if(!$muban){
            return 0;
        }
        //查询店铺名称
        $store_name = M('webpos_local_store')->where(['local_id' => $this->local_id])->find()['local_name'];
        $url = $_SERVER['SERVER_NAME'].'/First/wxOrdetails/order_id/'.$order_id.'/member_id/'.$member_id;
        //dump($url);die;
        $cs = array(
            'touser'=>$openId,
            'template_id'=>trim($muban['template_id']),
            'url'=>$url,
            'data'=>[
                'first'=>[
                    'value'=>'您好，您的订单已发货',
                    'color'=>"#173177",
                ],
                "keyword1"=>[
                    "value"=>$store_name,
                    "color"=>"#173177",
                ],
                "keyword2"=>[
                    "value"=>$order_id,
                    "color"=>"#173177",
                ],
                "keyword3"=>[
                    "value"=>$logi_name,
                    "color"=>"#173177",
                ],
                "keyword4"=>[
                    "value"=>$logi_no,
                    "color"=>"#173177",
                ],
                "remark"=>[
                    "value"=>"请注意查收！",
                    "color"=>"#173177",
                ],
            ],
        );
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
        $obj = new WeixinEvent();
        $msg = $obj->parameterPostBtn($cs,$url,1);
        if($msg['errcode'] != 0){
            $add_data = [
                'order_id' => $order_id,
                'openid' => $openId,
                'type' => 1,
                'errcode' => $msg['errcode'],
                'errmsg' => $msg['errmsg'],
                'create_time' => time(),
                'status' => 2,
            ];
            M('push_message_log')->add($add_data);
            return 2;
        }else{
            return 1;
        }

    }

    /**
     * 完成操作
     */
    public function finishOrder($order_id){
        $Model = new B2cOrdersModel();


        $save['received_status'] = '1';
        $save['comment_status'] = '1';
        $save['order_msg'] = '待评价';
        $save['received_time'] = time();


        $result = M('b2c_orders')->where(['order_id'=>$order_id,'local_id'=>session('userInfo.local_id')])->save(['received_status'=>'1','comment_status'=>'1','order_msg'=>'待评价','received_time'=>time()]);




        if($result){

            $delivery_data = ['item_type' => '3', 'create_time' => time()];
            $delivery_stat = M('b2c_delivery_process')->where(['order_id'=>$order_id,'item_type'=>2])->save($delivery_data);


            //操作日志
            $finishArr = array(
                'rel_id'=>$order_id,
                'op_id'=>session('userInfo.local_id'),
                'op_name'=>session('userInfo.username'),
                'alttime'=>time(),
                'bill_type'=>'order',
                'behavior'=>'received_status',
                'result'=>'SUCCESS',
                'log_text'=>'店铺后台操作自提确认收货',
            );

            $actionRes = M('b2c_order_log')->data($finishArr)->add();
            if($actionRes){
                $this->ajaxReturn(array('msg'=>'操作成功','status'=>1));
            }else{
                $this->ajaxReturn(array('msg'=>'操作失败','status'=>0));
            }

        }


    }

    public function eExcel(){


        /*$title = array("订单号","是否自提","下单时间","配送方式","配送时间","客户备注","订单备注","会员名称","支付方式","收货人","收货人手机","配送费用","订单总额","付款状态","发货状态");*/

        $title = array(
            array('order_id','订单号'),
            array('is_zt','是否自提'),
            array('createtime','下单时间'),
            array('shipping','配送方式'),
            array('ship_time','配送时间'),
            array('memo','客户备注'),
            array('mark','订单备注'),
            array('login_account','会员名称'),
            array('payment','支付方式'),
            array('ship_name','收货人'),
            array('ship_mobile','收货人手机'),
            array('cost_freight','配送费用'),
            array('total_amount','订单总额'),
            array('pay_status','付款状态'),
            array('ship_status','发货状态')


        );


        $data = $_POST;

        $datStr = implode(',',$data['checkName']);
        //查询数据
        $strData['o.order_id'] = array('in',$datStr);


        $seData = M('b2c_orders o')
            ->join("left join ".C('DB_PREFIX')."b2c_members m on o.member_id = m.member_id")
            ->where([$strData,array('o.local_id'=>session('userInfo.local_id'))])
            ->field("o.order_id,o.is_zt,o.createtime,o.shipping,o.ship_time,o.memo,o.mark_text,m.nickname,o.payment,o.ship_name,
            o.ship_mobile,o.cost_freight,o.total_amount,o.pay_status,o.ship_status")->select();

        foreach ($seData as $k=>$item){
            $seData[$k]['order_id'] = "'".$item['order_id'];
            $seData[$k]['is_zt'] = $item['is_zt']?"自提订单":"普通订单";
            $seData[$k]['createtime'] = "'".date('Y-m-d H:i:s',$item['createtime']);
            $seData[$k]['shipping'] = $item['shipping']; //配送方式
            $seData[$k]['ship_time'] = $item['ship_time'];//配送时间
            $seData[$k]['memo'] = $item['memo'];//客户附言

            if(!empty($item['mark_text'])){
                $mark =unserialize( $item['mark_text']);
                $markContent = end($mark);
            }
            $seData[$k]['mark_text'] =  $markContent['mark_text'];
            $seData[$k]['login_account'] = $item['login_account'];//会员名称
            $seData[$k]['payment'] = $item['payment'];//支付方式
            $seData[$k]['ship_name'] = $item['ship_name'];//收货人姓名
            $seData[$k]['ship_mobile'] = "'".$item['ship_mobile'];//收货手机
            $seData[$k]['cost_freight'] = $item['cost_freight'];//配送费用
            $seData[$k]['total_amount'] = $item['total_amount'];//订单总额

            if($item['pay_status']==1){
                $item['pay_status'] = "已支付";
            }else if($item['pay_status']==0){
                $item['pay_status'] = "未支付";
            }

            $seData[$k]['pay_status'] = $item['pay_status'];//付款状态

            if($item['ship_status']==1){
                $item['ship_status'] = "已发货";
            }else if($item['ship_status']==2){
                $item['ship_status'] = "部分发货";
            }else if($item['ship_status']==0){
                $item['ship_status'] = "未发货";
            }

            $seData[$k]['ship_status'] = $item['ship_status'];//发货状态


        }



        $this->exportexcel('订单',$title,$seData);


    }

    public function exprotAllOrder(){

        $view = I('get.view',0,'intval');
        $sub = array(
            0 => array('o.pay_status' => '1', 'o.ship_status' => array('in', array('0', '2')), 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')),// 待发货
            1 => array('o.pay_status' => '1', 'o.ship_status' => '1', 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')),// 已发货
            2 => array('o.pay_status' => '1', 'o.ship_status' => '1', 'o.received_status' => '1', 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')), //已收货  部分发货，不能确认收货 提示货没发完，收货定时任务，判断 发货状态是 1
            3 => array('o.pay_status' => '0', 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')),//待支付
            4 => array('o.status' => 'dead', 'o.local_id' => session('userInfo.local_id')),//已经作废【未支付订单超时】，定时返回库存
            5 => array('o.status' => 'finish', 'o.local_id' => session('userInfo.local_id')),//已完成
            //6=>array('o.pay_status'=>'1','o.is_zt'=>1,'o.status'=>'active','o.local_id'=>session('userInfo.local_id')),//店铺自提  [完成按钮]  状态 finish 库存操作
            6 => array('o.local_id' => session('userInfo.local_id')),
        );
        $where[] = $sub[$view];
        $title = array(
            array('order_id','订单号'),
            array('is_zt','是否自提'),
            array('createtime','下单时间'),
            array('shipping','配送方式'),
            array('ship_time','配送时间'),
            array('memo','客户备注'),
            array('mark','订单备注'),
            array('login_account','会员名称'),
            array('payment','支付方式'),
            array('ship_name','收货人'),
            array('ship_mobile','收货人手机'),
            array('cost_freight','配送费用'),
            array('total_amount','订单总额'),
            array('pay_status','付款状态'),
            array('ship_status','发货状态')
        );

        $orderList =  M('b2c_orders o')->field("o.*,m.login_account")
            ->join("left join " . C('DB_PREFIX') . "pam_members m on o.member_id = m.member_id")
            ->where($where)
            ->order('o.createtime desc')->select();

        foreach ($orderList as $k=>$item) {
            $seData[$k]['order_id'] = "'" . $item['order_id'];
            $seData[$k]['is_zt'] = $item['is_zt'] ? "自提订单" : "普通订单";
            $seData[$k]['createtime'] = "'" . date('Y-m-d H:i:s', $item['createtime']);
            $seData[$k]['shipping'] = $item['shipping']; //配送方式
            $seData[$k]['ship_time'] = $item['ship_time'];//配送时间
            $seData[$k]['memo'] = $item['memo'];//客户附言

            if (!empty($item['mark_text'])) {
                $mark = unserialize($item['mark_text']);
                $markContent = end($mark);
            }
            $seData[$k]['mark_text'] = $markContent['mark_text'];
            $seData[$k]['login_account'] = $item['login_account'];//会员名称
            $seData[$k]['payment'] = $item['payment'];//支付方式
            $seData[$k]['ship_name'] = $item['ship_name'];//收货人姓名
            $seData[$k]['ship_mobile'] = "'" . $item['ship_mobile'];//收货手机
            $seData[$k]['cost_freight'] = $item['cost_freight'];//配送费用
            $seData[$k]['total_amount'] = $item['total_amount'];//订单总额

            if ($item['pay_status'] == 1) {
                $item['pay_status'] = "已支付";
            } else if ($item['pay_status'] == 0) {
                $item['pay_status'] = "未支付";
            }

            $seData[$k]['pay_status'] = $item['pay_status'];//付款状态

            if ($item['ship_status'] == 1) {
                $item['ship_status'] = "已发货";
            } else if ($item['ship_status'] == 2) {
                $item['ship_status'] = "部分发货";
            } else if ($item['ship_status'] == 0) {
                $item['ship_status'] = "未发货";
            }
            $seData[$k]['ship_status'] = $item['ship_status'];

        }
        $isDes = array(
            0=>'待发货订单',
            1=>'已发货订单',
            2=>'已收货订单',
            3=>'待支付订单',
            4=>'已作废订单',
            5=>'已完成订单',
            6=>'全部订单',
        );

        $this->exportexcel($isDes[$view], $title, $seData);

    }

    public function exportexcel($expTitle,$expCellName,$expTableData){

        $data_time = date('Y-m-d',time());
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName =$data_time.$expTitle;//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;


    }




    public function orderPrinting(){
        $Model = new B2cOrdersModel();
        $order_detail = $Model->orderDetail(I('get.order_id',0));

        $order_detail['printing']['member_name']=  M('b2c_members')->where(['member_id'=>$order_detail['detail']['member_id']])->find()['mobile'];

        /* 冉 3-8 优惠金额计算*/
        $old_price = 0;
        foreach ($order_detail['product'] as $k=>$v){
            $old_price += $v['amount'];
        }

        $order_detail['youhui'] = $old_price - $order_detail['detail']['total_amount'] + $order_detail['detail']['cost_freight'];

        $this->assign('printing',$order_detail);
        $this->display('Orders/orderPrinting');
    }
    /*
     * 打印配合单颜色变化
     */
    public function printChangeColor($order_id){
       $res = M('b2c_orders')->where(['order_id'=>$order_id])->save(['is_print'=>'1']);
       if($res !==false ){
           return $this->ajaxReturn(['status'=>1,'msg'=>'已打印']);
       }
    }


    public function orderPrintDelivery(){
        $Model = new B2cOrdersModel();
        $order_detail = $Model->orderDetail(I('get.order_id',0));

        $order_detail['printing']['member_name']=  M('b2c_members')->where(['member_id'=>$order_detail['detail']['member_id']])->find()['mobile'];


        //发货地址信息
        $dlyList = M('express_dly_center')->where(['local_id'=>session('userInfo.local_id')])->select();
        //快递单模板
        $dlyTmpl = M('express_print_tmpl')->where(['local_id'=>session('userInfo.local_id'),'shortcut'=>'true'])->select();

        $this->assign('dlyList',$dlyList);
        $this->assign('dlyTmpl',$dlyTmpl);



        $this->assign('printDelivery',$order_detail);
        $this->display('Orders/orderPrintDelivery');
    }
    //保存订单地址
    public function saveDliAddr(){

        $data =$_POST['order'];
        $res =  M('b2c_orders')->where(['order_id'=>$data['order_id']])->save($data);

        if($res !== false){
            $this->ajaxReturn(array('msg'=>'保存成功','status'=>1));
        }else{
            $this->ajaxReturn(array('msg'=>'保存失败','status'=>0));
        }
    }

    public function changeContent(){
        $data= $_POST['id'];
        $Sdly = M('express_dly_center')->where(['dly_center_id'=>$data,'local_id'=>session('userInfo.local_id')])->find();
        $html = "        
            <table border='0' cellpadding='0' cellspacing='0' style='font-size: 12px;'>
                <tbody><tr>
                    <th>姓名：</th><td>".$Sdly['name']."</td>
                    <th>地区：</th><td>".$Sdly['region']."</td>
                </tr>
                <tr>
                    <th>邮编：</th><td>".$Sdly['zip']."</td>
                    <th>地址：</th><td>".$Sdly['address']."</td>
                </tr>
                <tr>
                    <th>手机：</th><td>".$Sdly['cellphone']."</td>
                    <th>电话：</th><td>".$Sdly['phone']."</td>
                </tr>
                </tbody>
            </table>        
        ";
        $this->ajaxReturn(array('msg'=>$html,'status'=>1));
    }
    //打印快递单
    public function orderPrintKd(){

        $data = I();

        /*
        $data['shop_name'] = '店铺名称'; //网店名称 1
        $data['ship_name'] = '收货人姓名';; //收货人姓名 1
        $data['ship_area'] = '收货人地区'; //收货人地区 1
        $data['ship_addr'] = '收货人地址'; //收货人地址 1

        $data['ship_mobile'] = '收货人手机';; //收货人手机 1

        $data['ship_detail_addr'] = '收货人-地区+详细地址'; 1


        $data['dly_name'] = '发货人姓名'; //发货人姓名 1
        $data['dly_area'] = '发货人地区'; //发货人地区 1
        $data['dly_address'] = '发货人地址'; //发货人地址 1
        $data['dly_tel'] = '发货人电话'; //发货人电话 1
        $data['dly_mobile'] = '发货人手机'; //发货人手机
        $data['dly_zip'] = '发货人邮编'; //发货人邮编 1

        $data['date_y'] = '当日日期-年'; //当日日期-年 1
        $data['date_m'] = '当日日期-月'; //当日日期-月 1
        $data['date_d'] = '当日日期-日'; //当日日期-日 1

        $data['order_id'] = '订单-订单号'; //订单-订单号 1
        $data['order_price'] = '订单总金额'; //订单总金额 1
        $data['order_weight'] = '订单物品总重量'; //订单物品总重量 1
        $data['order_count'] = '订单-物品数量'; //订单-物品数量 1
        $data['order_memo'] = '订单-备注'; //订单-备注 1
        $data['ship_time'] = '订单-送货时间'; //订单-送货时间 1

        $data['tick']= '√'; //对号 1

        $data['member_name'] = '会员用户名'; //会员用户名 1
        $data['order_name'] = '订单商品名称'; //订单商品名称
        $data['order_name_a'] = '订单商品名称+数量'; //订单商品名称+数量
        $data['order_name_as']='订单商品名称+规格+数量'; //订单商品名称+规格+数量
        $data['order_name_ab'] = '订单商品名称+货号+数量'; //订单商品名称+货号+数量
        */

        $orderDetail =  M('b2c_order_items i')
            ->join("left join ".C('DB_PREFIX')."b2c_orders o on o.order_id = i.order_id")
            ->where(['i.order_id'=>$data['order_id'],'o.local_id'=>session('userInfo.local_id')])
            ->field("o.*,i.*")
            ->select();

        $deData = array();
       foreach ($orderDetail as $k=>$value){
           $deData['ship_name'] =  $value['ship_name'];
           $deData['ship_area'] =  $value['ship_area'];
           $deData['ship_addr'] =  $value['ship_addr'];
           $deData['ship_mobile'] =  $value['ship_mobile'];


           $deData['ship_detail_addr'] =  str_replace('/','',$value['ship_area']).$value['ship_addr'];
           $deData['order_price'] =  $value['total_amount'];
           $deData['order_weight'] =  $value['weight'];
           $deData['order_count'] =  $value['itemnum'];
           $deData['memo'] =  $value['memo'];
           $deData['ship_time'] =  $value['ship_time'];

           $deData['member_id'] =  $value['member_id'];
           $deData['product']['order_name'][$k] = $value['name'];
           $deData['product']['order_name_a'][$k] = $value['name'].'&nbsp;&nbsp;+数量：'.$value['nums'];
           $deData['product']['order_name_as'][$k] = $value['name'].$value['addon'].'&nbsp;&nbsp;+数量'.$value['nums'];
           $deData['product']['order_name_ab'][$k] = $value['name'].'&nbsp;&nbsp;'.$value['bn'].'&nbsp;&nbsp;+数量'.$value['nums'];
       }

        $deData['shop_name'] =  M('webpos_local_store')->where(['local_id'=>session('userInfo.local_id')])->find()['local_name'];

        $deliDetail =  M('express_dly_center')->where(['dly_center_id'=>$data['dly_center']])->find();


        $deData['dly_name'] = $deliDetail['name'];
        $deData['dly_area'] = $deliDetail['region'];
        $deData['dly_address'] = $deliDetail['address'];
        $deData['dly_tel'] = $deliDetail['phone'];
        $deData['dly_mobile'] = $deliDetail['cellphone'];
        $deData['dly_zip'] = $deliDetail['zip'];
        $deData['date_y'] = date("Y");
        $deData['date_m'] = date("m");
        $deData['date_d'] = date("d");
        $deData['order_id'] = $data['order_id'];


        $deData['tick'] = '√';
        $deData['member_name'] =  M('b2c_members')->where(['member_id'=>$deData['member_id']])->find()['mobile'];

        $muBan =  M('express_print_tmpl')->where(['prt_tmpl_id'=>$data['prt_tmpl_id']])->find();

        $muBan['prt_tmpl_data'] =  json_decode($muBan['prt_tmpl_data'],TRUE);
        foreach ($muBan['prt_tmpl_data'] as $k=>$value){
            $str_pos = strpos($value['keyword'],'order_name');

            if($str_pos === false){
                $muBan['prt_tmpl_data'][$k]['vName'] =  $deData[$value['keyword']];
            }else{
                $muBan['prt_tmpl_data'][$k]['vName'] =  $deData['product'][$value['keyword']];

            }

        }
        $deData['prt_tmpl_width'] = $muBan['prt_tmpl_width'];
        $deData['prt_tmpl_height'] = $muBan['prt_tmpl_height'];

       // print_r($deData);
      //  print_r($muBan);





        $html ='';
        $html = "<div id='ssss'><div id=\"content\" style=\"width:".$muBan['prt_tmpl_width']."px;height:".$muBan['prt_tmpl_height']."px\">";
        foreach ($muBan['prt_tmpl_data'] as $k=>$item){

            if(is_array($item['vName'])){

                    foreach ($item['vName'] as $k=>$v){
                       $aaa .= $v.'<br>';
                    }
                $item['vName'] = $aaa;

            }else{
                $item['vName'];
            }


            $htm[$k] = "<div class=\"info ui-widget-content ui-resizable ui-draggable ui-draggable-handle\""." style=\"width: 170px; 
           height: 20px; position: absolute; top: ".$item['y']."px; left: ".$item['x']."px;\">"
            ."<span class=\"key-name\">".$item['vName']."</span></div>";
            $html .= $htm[$k];
        }

        $top = $muBan['prt_tmpl_height'] +100;
        $html = $html."</div></div>"." <div id=\"print_confirm\" class=\"noprint\" style=\"top: ".$top."px;\"><div id=\"btn_print\"></div></div>"
            ."<style>#btn_print {
            width: 71px;
            height: 24px;
            background-image: url(/Public/Home/images/btn_print.gif);
            cursor: pointer;
            margin-left: auto;
            margin-right: auto;
        }
        #print_confirm {
            width: 100%;
            height: 30px;
            border-top: 1px solid #999999;
            padding-top: 4px;
            background-color: #5473ae;
            position: absolute;
        }
    </style>"."<script src=\"/Public/Home/js/jquery.PrintArea.min.js\"></script>".
            "<script>$(\"#btn_print\").click(function(){
                    $(\"#content\").printArea();
             });</script>";

        $w = $muBan['prt_tmpl_width']+100;
        $h = $muBan['prt_tmpl_height']+180;

        $this->ajaxReturn(array('html'=>$html,'width'=>$w,'height'=>$h));
       /* $this->assign('deData',$deData);
        $this->assign('muBan',$muBan['prt_tmpl_data']);
        $this->display('Orders/orderPrintKd');*/
    }

}